#ifndef _ZSTACK_TIMER_H_
#define _ZSTACK_TIMER_H_

#include <app.h>

//_____________________________________________________________________________
// based on tick (default: 1 tick = 1 ms)
// call in timer ISR
// after expire, send IP to event queue, then trigger CLOCK command
//

struct timer
{
    U32 period;   // ms
    U32 offset;   // ms
    U32 IP;       // SWIP
    U64 expire;   // ms
};

//_____________________________________________________________________________
//

static struct timer softimer[] = {
    {1000, 0, SWIP_TEST},
};

static U64 tick_cnt = 0;

//_____________________________________________________________________________
//

void timer_update(void)
{
    U32 i;

    tick_cnt++;

    for (i = 0; i < ARRAY_SIZE(softimer); i++)
    {
        if (tick_cnt >= softimer[i].expire)
        {
            softimer[i].expire += softimer[i].period;

            swip_call(softimer[i].IP, SWIP_CMD_CLOCK_DRIVE, 0, 0);
        }
    }
}

//_____________________________________________________________________________
//

U32 software_timer_event_handler(U32 ip, U32 cmd, U32 param1, U32 param2)
{
    U32 i;

    switch (cmd)
    {
    case SWIP_CMD_LOAD:
        for (i = 0; i < ARRAY_SIZE(softimer); i++)
        {
            softimer[i].expire = softimer[i].offset + softimer[i].period;
        }
        break;
    case SWIP_CMD_CLOCK_DRIVE:
        timer_update();
        break;
    }

    return 0;
}

#endif
